from fastapi import APIRouter, Depends
from app.api.schemas.user import Token, UserDataBase
from app.db.crud.user_crud import check_user, get_password_hash
from app.db.crud import get_db
from sqlalchemy.orm import Session
from datetime import timedelta
from app.setting.setting import config
from app.common.security import create_token
from app.common.response_code import resp_200, resp_401

loginAPI = APIRouter()

# 登录接口
@loginAPI.post("/login", summary="用户登录认证接口")
async def login(login_user: UserDataBase, db: Session=Depends(get_db)):
    user = check_user(db, login_user)
    if not user:
        return resp_401(login_user, message="用户名或密码错误")
    # 过期时间
    access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    # refresh_token_expires = timedelta(minutes=config.REFRESH_TOKEN_EXPIRE_MINUTES)   // refresh_token 暂不使用

    # 把username加密
    access_token = create_token(
        data={"sub": user.userName}, expires_delta=access_token_expires
    )
    # refresh_token = create_token(
    #     data={"sub": user.userName}, expires_delta=refresh_token_expires
    # )
    token = Token(userName=user.userName, access_token=access_token)
    # token = Token(userName=user.userName, access_token=access_token, refresh_token=refresh_token)
    return resp_200(token)


@loginAPI.get("/getPasswordHash", summary="临时用获取哈希密码")
async def getPasswordHash(pwd: str, db: Session=Depends(get_db)):
    return get_password_hash(pwd)
